package l1j.opqlo.Timer.Controler;

import java.util.Collection;
import java.util.Iterator;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.opqlo.Server.L1World.L1World;
import l1j.server.Thread.PcOtherThreadPool;
import l1j.server.server.datatables.lock.HellTimeReading;
import l1j.server.server.model.L1Teleport;
import l1j.server.server.model.Instance.L1PcInstance;


/**
 * PC 地獄模式處理 時間軸
 * @author dexc
 *
 */
public class PcHellTimer extends TimerTask {

	private static final Logger _log = Logger.getLogger(PcHellTimer.class.getName());

	private ScheduledFuture<?> _timer;

	public void start() {
		final int timeMillis = 1100;
		_timer = PcOtherThreadPool.get().scheduleAtFixedRate(this, timeMillis, timeMillis);
	}

	@Override
	public void run() {
		try {
			final Collection<L1PcInstance> all = L1World.getInstance().getAllPlayers();
			// 不包含元素
			if (all.isEmpty()) {
				return;
			}
			
			for (final Iterator<L1PcInstance> iter = all.iterator(); iter.hasNext();) {
				final L1PcInstance tgpc = iter.next();
				if(tgpc.isDead()){
					continue;
				}
				int time = tgpc.getHellTime();
				// 非地獄狀態
				if (time <= 0) {
					continue;
				}
				time--;
				check(tgpc, time);
				Thread.sleep(1);
			}
			
			/*for (final L1PcInstance tgpc : all) {
				int time = tgpc.getHellTime();
				// 非地獄狀態
				if (time <= 0) {
					continue;
				}
				time--;
				check(tgpc, time);
				Thread.sleep(1);
			}*/

		} catch (final Exception e) {
			_log.log(Level.SEVERE ,"PC 地獄模式處理時間軸異常重啟", e);
			PcOtherThreadPool.get().cancel(_timer, false);
			final PcHellTimer hellTimer = new PcHellTimer();
			hellTimer.start();
		}
	}

		private static final int locx = 32788;
		private static final int locy = 32795;
		private static final short mapid = 1784;
	/**
	 * 檢查地獄模式時間
	 * @param tgpc
	 * @param time
	 */
	private static void check(final L1PcInstance tgpc, final Integer time) {
		if (time > 0) {
			// 地獄以外に居るときは地獄へ強制移動
			if (tgpc.getMapId() != mapid) {
//				tgpc.setTeleportX(locx);
//				tgpc.setTeleportY(locy);
//				tgpc.setTeleportMapId(mapid);
//				tgpc.setTeleportHeading(0);
//				Teleportation.actionTeleportation(tgpc);
				L1Teleport.teleportByMagic(tgpc, locx, locy, mapid, 5, false);
			}
			// 更新
			tgpc.setHellTime(time);

		} else {
			// 時間到
			tgpc.setHellTime(0);
			HellTimeReading.get().EndHell(tgpc.getId());
			// 未斷線移除狀態
			if (tgpc.getNetConnection() != null) {
				outPc(tgpc);
			}
		}
	}

	/**
	 * 離開地獄模式
	 * @param tgpc
	 */
	private static void outPc(final L1PcInstance tgpc) {
		try {
			if (tgpc != null) {
				tgpc.endHell();
			}
			
		} catch (final Exception e) {
			_log.log(Level.SEVERE ,e.getLocalizedMessage(), e);
		}
	}
}
